import { authInfoApi, logoutApi } from '@/api/login'
import { staticUrl } from '@/utils/frame'
import defAvatar from '@/assets/images/profile.jpg'
import cache from '@/plugins/cache'
import { defineStore } from 'pinia'

const useUserStore = defineStore('user', {
  state: () => ({
    token: cache.local().get('vv__login_token', ''),
    id: '',
    name: '',
    avatar: defAvatar,
    roles: [],
    permissions: [],
    user: null
  }),
  actions: {
    // 登录
    login(token) {
      return new Promise((resolve, reject) => {
        if (token) {
          this.token = token
          cache.local().set('vv__login_token', token)
          resolve()
        } else {
          cache.local().clear('vv__login_token')
          reject('登录标识缺失')
        }
      })
    },
    // 获取用户信息
    AuthInfo() {
      return new Promise((resolve, reject) => {
        authInfoApi()
          .then(res => {
            const user = res.user
            const avatar = user.avatar ? staticUrl(user.avatar) : defAvatar

            if (res.roles && res.roles.length > 0) {
              this.roles = res.roles
              this.permissions = res.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.id = user.id
            this.name = user.nick_name
            this.avatar = avatar
            this.user = user
            resolve(res)
          })
          .catch(error => {
            console.log(error)
            reject(error.msg || '获取用户信息失败')
          })
      })
    },
    // 过期清除
    LogClear() {
      return new Promise(resolve => {
        cache.local().clear('vv__login_token')
        this.token = ''
        this.roles = []
        this.permissions = []
        resolve()
      })
    },
    // 退出系统
    logOut() {
      return new Promise(resolve => {
        logoutApi(this.token).finally(() => {
          cache.local().clear('vv__login_token')
          this.token = ''
          this.roles = []
          this.permissions = []
          resolve()
        })
      })
    }
  }
})

export default useUserStore
